﻿//------------------------------------------------------------------------------
// The contents of this file are subject to the Microsoft Public License (Ms-PL)
// You may obtain a copy of the License at http://psadmin.codeplex.com/license. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, 
// WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations 
// under the License.
// 
// The initial developer is Ben Foster (ben.foster@retroviz.com)
// Copyright (c) Retroviz Limited (http://www.retroviz.com).
// All Rights Reserved.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PSAdmin.Core.Domain;
using PSAdmin.Core.Security;

namespace PSAdmin.Web.Infrastructure
{
    public static class ControllerExtensions
    {
        public static bool IsAdminRequest(this SiteController controller) {
            return controller.User.IsInRole("Administrators");
        }

        public static bool CanExecuteScript(this SiteController controller, PSScript script, IEnumerable<UserRole> roles) {          
            foreach (var userRole in roles) {
                if (script.Roles.Contains(userRole))
                    return true;
            }
            return controller.IsAdminRequest();
        }

        public static UserEvent CreateEvent(this SiteController controller, int? scriptId, UserBehaviour behaviour, string scriptName, string scriptVariables, string scriptOutput) {
            return new UserEvent {
                Behaviour = behaviour,
                Username = controller.User.Identity.Name,
                HostName = controller.Request.UserHostName,
                IP = controller.Request.UserHostAddress,
                DateCreated = DateTime.Now,
                ScriptId = scriptId,
                ScriptName = scriptName,
                ScriptVariables = scriptVariables,
                ScriptOutput = scriptOutput,
            };
        }
    }
}
